<template>
  <div class="app-container">
    <el-row :gutter="24" type="flex" justify="between" class="padding">
      <el-col :span="12" class="titles">
        <span class="title">公告管理</span>
      </el-col>
      <el-col :span="12" class="right">
        <el-button type="primary" size="medium" @click="handleAdd">新增公告</el-button>
      </el-col>
    </el-row>
    <el-table
      v-loading="listLoading"
      :data="list"
      row-key="id"
      border
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column
        type="index"
        width="50">
      </el-table-column>
      <el-table-column
        prop="title"
        label="标题"
      />
      <el-table-column
        prop="content"
        label="内容"
      />
      <el-table-column
        prop="createTime"
        label="添加时间"
      />
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="title"  :visible.sync="dialogForm" @close="colse" width="40%" @opened="dialogOpened()" :modal-append-to-body="false" :append-to-body="true">
      <el-form ref="form" :model="form" size="mini" :rules="rules">
        <el-form-item label="排序" :label-width="formLabelWidth" prop="sequence">
          <el-input v-model="form.sequence" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="标题" :label-width="formLabelWidth" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="发布时间" :label-width="formLabelWidth" prop="createTime">
          <el-date-picker
            v-model="form.createTime"
            type="datetime"
            placeholder="请选择发布时间"
            default-time="12:00:00"
          />
        </el-form-item>
        <el-form-item label="内容" :label-width="formLabelWidth" prop="content">
          <div id="content" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogForm = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getNotice, noticeRemove, saveNotice } from '@/api/admin/notice'
import E from 'wangeditor'
import { parseTime } from '@/utils/util'
import FileManage from '@/components/FileManage'

export default {
  components: {
    FileManage
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      dialogForm: false,
      form: {
        sequence: '',
        title: '',
        createTime: '',
        content: ''
      },
      rules: {
        sequence: [
          { required: true, message: '请输入排序', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        createTime: [
          { required: true, message: '请输入发布时间', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ]
      },
      title: '',
      formLabelWidth: '120px',
      optionProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        checkStrictly: true
      },
      msg: '<h2><img src=www.zhongxinyul2.com"http://www.078881.cn img.baidu.com/hi/jx2/j_0003.gif"/>Vue + UEditor + v-model双向绑定</h2>',
      myConfig: {
        // 编辑器不自动被内容撑高
        autoHeightEnabled: false,
        // 初始容器高度
        initialFrameHeight: 240,
        // 初始容器宽度
        initialFrameWidth: '100%',
        // 上传文件接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
        serverUrl: 'https://www.xunyingcg.com/companyAuth/api//oss/uploadFileToOss',
        // UEditor 资源文件的存放路径，如果你使用的是 vue-cli 生成的项目，通常不需要设置该选项，vue-ueditor-wrap 会自动处理常见的情况，如果需要特殊配置，参考下方的常见问题2
        UEDITOR_HOME_URL: '/static/UEditor/'
      },
      fileDialog: false,
      fileType: 'image',
      editor: null,
      editorDialog: false,
      editorFileType: 'image',
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 富文本编辑器
    dialogOpened() {
      const that = this
      // 扩展菜单
      const { BtnMenu } = E
      class upimg extends BtnMenu {
        constructor(editor) {
          const $elem = E.$(`<div class="w-e-menu" data-title="上传图片"><el-button>图片</el-button></div>`)
          super($elem, editor)
        }
        clickHandler() {
          that.editorFileType = 'image'
          that.editorDialog = true
        }
        tryChangeActive() {}
      }
      class upfile extends BtnMenu {
        constructor(editor) {
          const $elem = E.$(`<div class="w-e-menu" data-title="上传附件"><el-button>附件</el-button></div>`)
          super($elem, editor)
        }
        clickHandler() {
          that.editorFileType = 'word'
          that.editorDialog = true
        }
        tryChangeActive() {}
      }
      class upvideo extends BtnMenu {
        constructor(editor) {
          const $elem = E.$(`<div class="w-e-menu" data-title="上传视频"><el-button>视频</el-button></div>`)
          super($elem, editor)
        }
        clickHandler() {
          that.editorFileType = 'video'
          that.editorDialog = true
        }
        tryChangeActive() {}
      }
      class clear extends BtnMenu {
        constructor(editor) {
          const $elem = E.$(`<div class="w-e-menu" data-title="清空内容"><el-button>清空</el-button></div>`)
          super($elem, editor)
        }
        clickHandler() {
          that.editor.txt.clear()
        }
        tryChangeActive() {}
      }
      that.editor = new E('#content')
      that.editor.config.showLinkImg = false; //隐藏‘网络图片’的按钮
      that.editor.config.uploadImgServer = 'https://www.xunyingcg.com/companyAuth/api/oss/uploadFileToOss' // 上传图片到服务器
      that.editor.config.uploadImgMaxSize = 2 * 1024 * 1024; // 将图片大小限制为 2M
      that.editor.config.uploadImgMaxLength = 5 // 限制一次最多上传 5 张图片
      that.editor.config.uploadFileName = 'file'
      that.editor.config.uploadImgTimeout = 30000 // 将 timeout 时间改为 3s
      that.editor.config.menus = [
        'head',
        'bold',
        'fontSize',
        'fontName',
        'italic',
        'underline',
        'strikeThrough',
        'indent',
        'lineHeight',
        'foreColor',
        'backColor',
        'link',
        'list',
        'todo',
        'justify',
        'quote',
        'emoticon',
        'image',
        'video',
        'table',
        'code',
        'splitLine',
        'undo',
        'redo',
      ]
      that.editor.config.uploadImgHooks = {
        customInsert: function(insertImgFn, result) {
          // result 即服务端返回的接口
          console.log('customInsert', result)

          // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
          insertImgFn(result.data)
        }
      }
      that.editor.config.height = 500
      that.editor.config.focus = false
      that.editor.config.placeholder = ''
      that.editor.config.onchange = (newHtml) => {
        that.form.content = newHtml
      }
      that.editor.create()
      that.editor.txt.html(that.form.content)
    },
    handleAvatarSuccess(res, file) {
      this.form.imgUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif' ||
        file
          .type === 'image/webp'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片JPG或者PNG格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    uploadRequest(file) {
      console.log(file)
      // this.form.imgUrl = URL.createObjectURL(file.raw)
    },
    colse() {
      this.editor.destroy()
      this.editor = null
      this.form = {
        sequence: '',
        title: '',
        // createTime: '',
        content: ''
      }
    },
    handleAdd() {
      this.dialogForm = true
      this.title = '新增公告'
    },
    handleEdit(index, row) {
      this.dialogForm = true
      this.form = JSON.parse(JSON.stringify(row))
      this.title = '修改公告'
    },
    submit() {
      this.$refs.form.validate((vaild, done) => {
        if (vaild) {
          console.log(this.form.createTime)
          if (this.form.createTime) {
            this.form.createTime = parseTime(new Date(this.form.createTime), 'y-m-d h:i:s')
          }
          saveNotice(this.form).then(response => {
            this.getList()
            this.dialogForm = false
            this.form = {
              sequence: '',
              title: '',
              createTime: '',
              content: ''
            }
            this.$message({
              showClose: true,
              message: response.message,
              type: 'success'
            })
          })
        }
      })
    },
    handleDelete(index, row) {
      this.$confirm(
        '删除',
        '删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          noticeRemove(row.id).then(response => {
            this.getList()
            this.$message({
              showClose: true,
              message: response.message,
              type: 'success'
            })
          })
        })
    },
    getList() {
      this.listLoading = true
      getNotice().then(response => {
        this.list = response.data
        this.listLoading = false
      })
    }
  }
}
</script>

<style>
/deep/.el-form-item{
  margin-bottom: 0 !important;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style scoped>
.title{
  padding-left: 7px;
  font-size: 16px;
  font-weight: 500;
  line-height: 24px;
}
.right{
  display: flex;
  justify-content: flex-end;
}
.padding{
  margin-bottom: 20px;
}
.titles{
  display: flex;
  align-items: center;
}
.flex{
  padding-top: 20px;
}
</style>
